package m1;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接消息服务器
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);//默认的端口可以省略
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c=f.newConnection().createChannel();//连接

        //定义队列
        c.queueDeclare("helloworld", false, false, false, null);
        //收到消息后用来处理消息的回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {//回调对象
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                byte[] body = message.getBody();
                String msg = new String(body);
                System.out.println("收到："+msg);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };

        //从helloworld队列接收消息
         /*
        参数：
             1.队列
             2.ack模式，true-自动ack，false-手动ack
             3.处理消息的回调对象
             4.取消消息处理的回调对象
         */
        c.basicConsume("helloworld", true,deliverCallback,cancelCallback);

    }
}
